﻿using System.ComponentModel;
using System.IO;
using System.Xml.Serialization;
using TShooter.TfsWord.Common;
using TShooter.TfsWord.Xml;

namespace TShooter.TfsWord.TeamFoundation
{
    [XmlRoot("Document", Namespace = Consts.XmlNamespace)]
    public class DocumentInfo : XmlCustomPart<DocumentInfo>
    {
        #region Constructors and member variables

        private static readonly XmlSerializer _Serializer = new XmlSerializer(typeof (DocumentInfo));
        private readonly ConnectionInfo _ConnectionInfo = new ConnectionInfo();
        private readonly WorkItemInfoCollection _WorkItems = new WorkItemInfoCollection();

        public DocumentInfo()
        {
            _ConnectionInfo.PropertyChanged += ConnectionInfo_PropertyChanged;
            _WorkItems.ListChanged += WorkItems_ListChanged;
        }

        #endregion

        #region Event Handlers

        private void ConnectionInfo_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            OnPropertyChanged("ConnectionInfo");
        }

        private void WorkItems_ListChanged(object sender, ListChangedEventArgs e)
        {
            OnPropertyChanged("WorkItems");
        }

        #endregion

        #region Properties

        [XmlElement("ConnectionInfo")]
        public ConnectionInfo ConnectionInfo
        {
            get { return _ConnectionInfo; }
        }

        [XmlArray("WorkItems"), XmlArrayItem(typeof (WorkItemData))]
        public WorkItemInfoCollection WorkItems
        {
            get { return _WorkItems; }
        }

        [XmlIgnore]
        public bool IsDirty { get; set; }

        #endregion

        public string ToXml()
        {
            var sw = new StringWriter();
            _Serializer.Serialize(sw, this);

            return sw.ToString();
        }

        public static DocumentInfo FromXml(string xml)
        {
            var sw = new StringReader(xml);
            return (DocumentInfo) _Serializer.Deserialize(sw);
        }
    }
}